/**
 * 
 */
package leetCode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhong
 *
 */
public class RemoveOutermostParentheses {
	/**
	 * 可优化
	 * 
	 * @param S
	 * @return
	 */
	public String removeOuterParentheses(String S) {
		List<String> subs = new ArrayList<>();
		int leftCnt = 0;
		int start = 0;
		for (int i = 0; i < S.length(); i++) {
			if (S.charAt(i) == '(') {
				leftCnt++;
			} else {
				leftCnt--;
			}
			if (leftCnt == 0) {
				subs.add(S.substring(start, i + 1));
				start = i + 1;
			}
		}
		StringBuilder sBuilder = new StringBuilder();
		for (String string : subs) {
			sBuilder.append(string.substring(1, string.length() - 1));
		}
		return sBuilder.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
